﻿using System;
using System.Web;
using Domino;
using System.Runtime.InteropServices;
using System.Web.Script.Serialization;

namespace NotesCommonProjects
{
    /// <summary>NOTES_003：寫入/更新Notes資料庫文件API
    /// 將收到的資料寫入指定的Notes資料庫</summary>

    public class SendMailAgent : IHttpHandler
    {
        //宣告Notes物件
        public NotesSession Session;
        public NotesDatabase Db;
        //public NotesForm Form;
        public NotesView View;
        public NotesDocument TempDoc;
        public NotesDocument NewDoc;

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】建立NotesSession
                Session = new NotesSession();

                //Initialize方法會自動抓目前系統登入使用的Notes id檔, 並要求輸入密碼
                //Session.Initialize(NotesCF.MyIdPassword);
                Session.Initialize(NotesCF.AutoCCPTIdPassword); //AutoCCPT

                //【02】檢查POST來的參數
                if (String.IsNullOrEmpty(req.Form["EMAIL_OBJECT"]))
                    throw new Exception(NotesCF.ExceptionMessage_01);

                //【03】反序列化字串
                //NewNotesDocument ReceiveObject = SendMailCF.GetDummyQCObject();   //使用DummyObject測試
                JavaScriptSerializer objSerializer = new JavaScriptSerializer();
                NewNotesDocument ReceiveObject = objSerializer.Deserialize<NewNotesDocument>(Convert.ToString(req.Form["EMAIL_OBJECT"]));

                //【04】檢查收到的Json物件
                if (!SendMailCF.CheckReceiveObject(ReceiveObject))
                    throw new Exception(NotesCF.ExceptionMessage_05);

                //【05】操作Notes文件
                //取得指定的NotesDatabase
                Db = Session.GetDatabase(ReceiveObject.Server, ReceiveObject.Database, false);

                //取得指定的NotesForm
                //Form = Db.GetForm(DummyObject.Form);

                //取得指定的NotesView
                View = Db.GetView(ReceiveObject.View);

                //檢查此文件是否已存在
                TempDoc = View.GetDocumentByKey(ReceiveObject.Key);

                if (TempDoc == null)    //文件不存在
                {
                    //在VIEW下建立新文件
                    NewDoc = Db.CreateDocument();

                    //指定Form
                    NewDoc.ReplaceItemValue("Form", ReceiveObject.Form);

                    //將收到的EFLD值插入NotesDocument的Item中
                    SendMailCF.InsertNewValueIntoNotesDocument(NewDoc, ReceiveObject);

                    //將文件儲存在Notes Server中
                    string FilePath = ReceiveObject.AttachmentPath;
                    if (FilePath != null)
                    {
                        //檢查RichTextItem "Attachment"是否存在
                        NotesRichTextItem RichTextItem = (NotesRichTextItem)NewDoc.GetFirstItem("Attachment");
                        if (RichTextItem == null)
                            RichTextItem = NewDoc.CreateRichTextItem("Attachment");

                        NotesEmbeddedObject AttachFile = RichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, "", FilePath, "Attachment");
                    }

                    bool SaveSuccess = NewDoc.Save(true, false);
                    if (!SaveSuccess)
                        throw new Exception(NotesCF.ExceptionMessage_04);

                }
                else    //文件已存在
                {
                    //刪除附加檔
                    if (TempDoc.GetAttachment(TempDoc.GetItemValue("$FILE")[0]) != null)
                        TempDoc.GetAttachment(TempDoc.GetItemValue("$FILE")[0]).Remove();

                    //指定Form
                    TempDoc.ReplaceItemValue("Form", ReceiveObject.Form);

                    //將收到的EFLD值插入NotesDocument的Item中
                    SendMailCF.InsertNewValueIntoNotesDocument(TempDoc, ReceiveObject);

                    //將文件儲存在Notes Server中
                    string FilePath = ReceiveObject.AttachmentPath;
                    if (FilePath != null)
                    {
                        //檢查RichTextItem "Attachment"是否存在
                        NotesRichTextItem RichTextItem = (NotesRichTextItem)TempDoc.GetFirstItem("Attachment");
                        if (RichTextItem == null)
                            RichTextItem = TempDoc.CreateRichTextItem("Attachment");

                        NotesEmbeddedObject AttachFile = RichTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, "", FilePath, "Attachment");
                    }

                    bool SaveSuccess = TempDoc.Save(true, false);
                    if (!SaveSuccess)
                        throw new Exception(NotesCF.ExceptionMessage_04);
                }

                //【06】回傳結果
                string ReturnObject = "OK";
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(ReturnObject);

                //【07】寫入Log
                string LogContext = "【收到的JSON字串】 【" + Convert.ToString(req.Form["EMAIL_OBJECT"]) + "】"
                    + "【回傳結果】 【" + resultStr + "】";
                NotesCF.WriteLog(NotesCF.SendMailAgentLogDir, LogContext);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = NotesCF.Ex2Xml(ex, false);

                //寫入Log
                string LogContext = "【呼叫失敗】 【" + ex.Message + "】";
                NotesCF.WriteLog(NotesCF.SendMailAgentLogDir, LogContext);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();

                //釋放COM物件
                Marshal.FinalReleaseComObject(NewDoc);
                NewDoc = null;
                Marshal.FinalReleaseComObject(TempDoc);
                TempDoc = null;
                Marshal.FinalReleaseComObject(View);
                View = null;
                Marshal.FinalReleaseComObject(Db);
                Db = null;
                Marshal.FinalReleaseComObject(Session);
                Session = null;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}